<template>
  <SuperTable ref="superTableRef" search :pager="false" border align="center" header-title="用户管理" :columns="columns"
    :data-request="fetchData" :export-config="{}" @checkbox-change="checkboxChangeFn" @checkbox-all="checkboxChangeFn">
    <template #action>
      <span class="check-num">
        当前已选中
        <span style="margin: 0 5px; color: #1f59f7">{{ state.checkedList.length }}</span>
        条数据
      </span>
      <Dropdown>
        <template #overlay>
          <Menu @click="changeStateFn">
            <a-menu-item key="1">启用</a-menu-item>
            <a-menu-item key="0">禁用</a-menu-item>
          </Menu>
        </template>
        <Button :disabled="!state.checkedList.length" type="primary">批量操作</Button>
      </Dropdown>
      <Button type="primary" @click="showModalFn('新增')"><plus-outlined />添加用户</Button>
    </template>
  </SuperTable>

  <UmEditModal v-model:show-modal="state.showModal" :data="state.currentData" :title="state.currentTitle"
    @edit-modal-ok="refreshTableFn" />
</template>

<script setup lang="ts">
import SuperTable from '@/framework/components/core/super-table/super-table.vue';
import UmEditModal from '@/modules/platform-management/pages/user-management/components/um-edit-modal.vue';
import { VxeGridPropTypes } from 'vxe-table';
import type { TableColumnItem } from './columns';
import { baseColumns } from './columns';
import { reactive, ref } from 'vue';
import Button from '@/framework/components/basic/button/button.vue';
import { message, Menu, Dropdown, Modal } from 'ant-design-vue';
import { PlusOutlined } from '@ant-design/icons-vue';
import { userList, userDelete, resetPass, userEnable, userDisable, userDetail } from '@/api/user-data';
import { useUserStore } from '@/store/modules/user';
const ssoOrLogin = ref();
//true是sso登录,ubderfined是普通登录
ssoOrLogin.value = !!window.__POWERED_BY_WUJIE__;
/**
 * const
 */
const userStore = useUserStore();
/**
 * data
 */
const state: {
  currentTitle: string;
  showModal: boolean;
  currentData: any;
  checkedList: any[];
} = reactive({
  currentTitle: '',
  showModal: false,
  currentData: {},
  checkedList: [],
});

/**
 * fn
 */
const showModalFn = async (params: string) => {
  if (params === '新增') {
    state.currentData = {};
  } else {
    let res = await userDetail(state.currentData.id);
    res.result.roleIds = Object.values(res.result.roleList ?? {})
      .flat()
      ?.map((item) => item.id)
      ?.join();
    state.currentData.extData1 ? res.result.extData1 = true : res.result.extData1 = false
    state.currentData = res.result;
  }
  state.currentTitle = params;
  state.showModal = true;
};
const changeStateFn = async (e) => {
  Modal.confirm({
    title: '确认操作',
    content: '确认要进行本次操作？',
    onOk: async () => {
      if (e.key === '1') {
        await Promise.all(
          state.checkedList.map(async (item) => {
            await userEnable(item.id);
          }),
        );
      } else {
        await Promise.all(
          state.checkedList.map(async (item) => {
            await userDisable(item.id);
          }),
        );
      }
      message.success('操作成功！');
      refreshTableFn();
    },
  });
};

/**
 * table
 */
const superTableRef = ref<InstanceType<typeof SuperTable>>();
const columns: TableColumnItem[] = [
  ...baseColumns,
  {
    title: '操作',
    field: '$action',
    hideInSearch: true,
    align: 'center',
    fixed: 'right',
    width: 300,
    actions: ({ row }) => [
      {
        label: '修改',
        onClick: () => {
          state.currentData = row;
          showModalFn('修改');
        },
      },
      {
        label: '密码重置',
        ifShow: userStore.userInfo.id === 'superadmin' ? true : false,
        popConfirm: {
          title: '确认要重置用户密码？',
          onConfirm: async () => {
            const res = await resetPass(row.id);
            message.success(res?.message);
          },
        },
      },
      {
        ifShow: row?.extData1 ? false : true,
        label: '删除',
        popConfirm: {
          title: `确认要删除该用户（${row.username}）？`,
          onConfirm: async () => {
            await userDelete(row.id);
            message.success('操作成功！');
            refreshTableFn();
          },
        },
      },
    ],
  },
];
const fetchData = async (ori: VxeGridPropTypes.ProxyAjaxQueryParams) => {
  let data = superTableRef.value?.getFormModel();
  let params = {
    pageSize: ori.page.pageSize,
    pageNum: ori.page.currentPage,
    orderBy: [
      {
        field: 'createTime',
        order: 'desc',
      },
    ],
    ...data,
  };
  let res = await userList(params);
  return {
    data: res.result,
    pageIndex: 1,
    pageSize: 10,
    total: 100,
  };
};
const refreshTableFn = () => {
  superTableRef.value?.refreshTable();
};
const checkboxChangeFn = ({ records }) => {
  state.checkedList = records;
};
</script>

<style scoped lang="less"></style>
